#include <iostream>
#include "pine.h"

static std::mutex g_mutex;
static Logger::ptr g_logger = MYWEB_LOG_ROOT();

int main() {
    TcpServer *server = new TcpServer();


    Signal::signal(SIGINT, [&] {
        delete server;
        std::unique_lock<std::mutex> lock(g_mutex);
        MYWEB_LOG_INFO(g_logger) << "\nServer exit!" << std::endl;
        exit(0);
    });


    server->onConnect([](Connection *conn) {
        std::unique_lock<std::mutex> lock(g_mutex);
        MYWEB_LOG_INFO(g_logger) << "New connection fd: " << conn->socket()->fd() << std::endl;
    });

    server->onRecv([](Connection *conn) {
        if(conn->state() != Connection::Closed) {
            std::unique_lock<std::mutex> lock(g_mutex);
            MYWEB_LOG_INFO(g_logger) << "Message from client " << conn->read_buf()->c_str() << std::endl;
            conn->Send(conn->read_buf()->c_str());
        }
    });

    server->Start();

    delete server;
    return 0;
}
